/*
 * CAnimation.cpp
 *
 *  Created on: 07.04.2012
 *      Author: caffeine
 */
#include <ISceneManager.h>
#include "CAnimation.h"
#include "CAnimationRecord.h"

namespace lampe{
namespace animation{

lampe::String CAnimation::getName(){
	return name;
}

void CAnimation::setName(lampe::String n){
	name=n;
}

CAnimation::CAnimation(lampe::String n,irr::scene::ISceneManager*m){
	name=n;
	manager=m;
	mesh=manager->createSkinnedMesh();
	frameCount=0;
	needCreateBone=true;
}

irr::s32 CAnimation::indexOf(lampe::String name){
	for (irr::u32 i=0;i<records.size();i++)
		if (records[i]->getName()==name)
			return i;
	return -1;
}

IAnimationRecord*CAnimation::getAnimationByIndex(irr::u32 index){
	if (index>=records.size())
		return 0;
	return records[index];
}

IAnimationRecord*CAnimation::getAnimationByName(lampe::String name){
	irr::s32 index=indexOf(name);
	if (index<0)
		return 0;
	return getAnimationByIndex(index);
}

void CAnimation::useFor(lampe::String name,irr::scene::IAnimatedMeshSceneNode*node){
	IAnimationRecord*a=getAnimationByName(name);
	if (a)
		a->useFor(node);
}

irr::s32 CAnimation::indexOfRecord(IAnimationRecord*animation){
	for (irr::u32 i=0;i<records.size();i++)
		if (records[i]==animation)
			return i;
	return -1;
}

void CAnimation::useAnimation(irr::scene::IAnimatedMeshSceneNode*node){
	if (!node)
		return;
	if (!node->getMesh())
		return;
	((irr::scene::ISkinnedMesh*)node->getMesh())->useAnimationFrom(getMesh());
}

irr::scene::ISkinnedMesh*CAnimation::getMesh(){
	return mesh;
}

bool CAnimation::getNeedCreateBone(){
	return needCreateBone;
}

IAnimationRecord*CAnimation::addAnimationFromMesh(irr::scene::ISkinnedMesh*a,String name){
	a->grab();
	CAnimationRecord*b=new CAnimationRecord(frameCount,frameCount+a->getFrameCount(),name,a,this);
	frameCount+=a->getFrameCount();
	records.push_back(b);
	a->drop();
	needCreateBone=false;
	return b;
}

IAnimationRecord*CAnimation::addAnimationFromFile(boost::filesystem::path filename,String name){
	irr::scene::ISkinnedMesh*temp=(irr::scene::ISkinnedMesh*)manager->getMesh(filename.string().c_str());
	if (!temp)
		return 0;

	return addAnimationFromMesh(temp,name);
	//temp->drop();
}

CAnimation::~CAnimation(){
	for (irr::u32 i=0;i<records.size();i++){
		records[i]->drop();
	}
	records.clear();
	mesh->drop();
}

extern IAnimation*createSkinnedAnimation(lampe::String name,irr::scene::ISceneManager*manager){
		return new CAnimation(name,manager);
}

}//namespace animation
}//namespace irr
